package com.autotest.nore.scheduler;

import com.autotest.nore.dto.PlanDTO;
import com.autotest.nore.mapper.PlanMapper;
import com.autotest.nore.request.RunRequest;
import com.autotest.nore.service.RunService;
import org.apache.logging.log4j.core.util.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@EnableScheduling


public class PlanScheduler {

    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private RunService runService;

    public PlanScheduler(PlanMapper planMapper) {
        this.planMapper = planMapper;
    }

    // 每1分钟检查一次哪些计划需要执行
    @Scheduled(fixedRate = 60000)
    public void checkAndExecutePlans() {
        List<PlanDTO> activePlans = planMapper.findActivePlans();

        activePlans.forEach(plan -> {
            try {
                if (CronExpression.isValidExpression(plan.getCronExpression())) {
                    System.out.println(LocalDateTime.now() + " - 执行计划: ");
                    CronExpression cron = new CronExpression(plan.getCronExpression());
                    System.out.println(plan.getCronExpression());
                    if (cron.isSatisfiedBy(new Date())) {
                        System.out.println(LocalDateTime.now() + " 时间相等");
                        executePlan(plan);
                    }
                }
            } catch (Exception e) {
                System.err.println("计划[" + plan.getId() + "]执行出错: " + e.getMessage());
            }
        });
    }

    private void executePlan(PlanDTO plan) {
        System.out.println(LocalDateTime.now() + " - 执行计划: " + plan.getName() +
                " (ID: " + plan.getId() + ")");
        // 这里添加实际执行计划的业务逻辑
        RunRequest runRequest=new RunRequest();
        runRequest.setProjectId(plan.getProjectId());
        runRequest.setEnvironmentId(plan.getEnvironmentId());
        runRequest.setSourceId(plan.getId());
        runRequest.setSourceType("plan");
        runRequest.setSourceName(plan.getName());
        String userName = "system";
        runRequest.setRunUser(userName);
        String reportId = UUID.randomUUID().toString();
        runService.runPlan(runRequest,reportId);
    }

    public static void main(String[] args) {
        CronExpression cron = null;
        try {
            cron = new CronExpression("* 09 14 ? * MON");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(cron.isSatisfiedBy(new Date()));
    }

}
